//
//  TixingViewController.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/7/11.
//

import UIKit
import UserNotifications
import Toast

class TixingViewController: BaseViewController {
    
    private var bgView: UIView!
    private var switch_: UISwitch!
    private var pickView: UIPickerView!
    private var hourStr: String = "00"
    private var minuteStr: String = "00"

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear
        
        setupUI()
        firstData()
    }
    

    private func firstData() {
        
        switch_.isOn = false
        hourStr = "00"
        minuteStr = "00"
        let timeStr = LocalData().getDailyReminder()
        if timeStr.contains(":") {
            switch_.isOn = true
            let array = timeStr.components(separatedBy: ":")
            if array.count == 2 {
                let hour = array[0]
                let minute = array[1]
                pickView.selectRow(Int(hour)!, inComponent: 0, animated: false)
                pickView.selectRow(Int(minute)!, inComponent: 1, animated: false)
                hourStr = hour
                minuteStr = minute
            }
        }
    }

}

//设置UI
extension TixingViewController {
    
    private func setupUI() {
        bgView = UIView()
        bgView.backgroundColor = .white
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(200)
        }
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside)
        bgView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(50)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
        }
        
        let centerTitleLabel = UILabel()
        centerTitleLabel.text = "设置阅读提醒"
        centerTitleLabel.font = UIFont.systemFont(ofSize: 16)
        centerTitleLabel.textColor = kColor333333
        bgView.addSubview(centerTitleLabel)
        centerTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(closeBtn.snp.bottom).offset(10)
        }
        
        switch_ = UISwitch()
        switch_.addTarget(self, action: #selector(switchClick(st:)), for: .valueChanged)
        bgView.addSubview(switch_)
        switch_.snp.makeConstraints { make in
            make.centerY.equalTo(centerTitleLabel)
            make.right.equalTo(bgView).offset(-20)
        }
        
        pickView = UIPickerView()
        pickView.dataSource = self
        pickView.delegate = self
        bgView.addSubview(pickView)
        pickView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(centerTitleLabel.snp.bottom).offset(20)
            make.height.equalTo(200)
        }
        
        let addButton = UIButton()
        addButton.setTitle("确定", for: .normal)
        addButton.setTitleColor(.white, for: .normal)
        addButton.backgroundColor = kThemeColor
        addButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        addButton.layer.cornerRadius = 25
        addButton.layer.masksToBounds = true
        addButton.addTarget(self, action: #selector(confirmBtnClick), for: .touchUpInside)
        bgView.addSubview(addButton)
        addButton.snp.makeConstraints { make in
            make.left.equalTo(50)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.top.equalTo(pickView.snp.bottom).offset(30)
        }
    }
    
    //bgView以外区域
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let touch = touches.first {
            let location = touch.location(in: view)
            let convertPoint = view.convert(location, to: bgView)
            if !bgView.bounds.contains(convertPoint) {
                dismissBtnClick()
            }
        }
    }
}

extension TixingViewController {
    
    @objc private func dismissBtnClick() {
        
        dismiss(animated: true) {
            
        }
    }
    
    @objc private func switchClick(st: UISwitch) {
        switch_.isOn = st.isOn
    }
    
    
    @objc private func confirmBtnClick() {
        dismissBtnClick()
        
        if switch_.isOn {
            let timeStr = "\(hourStr):\(minuteStr)"
            LocalData().saveDailyReminder(timeStr: timeStr)
            addLocalNotice()
            UIWindow().currentWindow()?.makeToast("已设置书单阅读计划提醒！", duration: 2.0, position: CSToastPositionTop)
            
        } else {
            LocalData().deleteDailyReminder()
            deleteLocalNotice()
            UIWindow().currentWindow()?.makeToast("已取消提醒！", duration: 2.0, position: CSToastPositionTop)
        }
        
        
        
    }
}


extension TixingViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 24
        }
        return 60
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        var string = string2(row: row)
        if component == 0 {
            string = "\(string)时"
        } else {
            string = "\(string)分"
        }
        return string
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            self.hourStr = string2(row: row)
        }
        self.minuteStr = string2(row: row)
    }
    
    private func string2(row: NSInteger) -> String {
        var string = ""
        if row < 9 {
            string = "0\(row)"
        } else {
            string = "\(row)"
        }
        return string
    }
}

extension TixingViewController {
    fileprivate func addLocalNotice() {
        
        deleteLocalNotice()
        let content = UNMutableNotificationContent.init()
        content.title = "点滴书单"
        content.body = "您已设置提醒，快去阅读你的书单吧！"
        content.sound = UNNotificationSound.default
        
        var date = DateComponents()
        date.hour = Int(hourStr)
        date.minute = Int(minuteStr)
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        
        let request = UNNotificationRequest.init(identifier: "notification.daily", content: content, trigger: trigger)
        let center = UNUserNotificationCenter.current()
        center.add(request) { error in
            print(error ?? "")
        }
        
    }
    fileprivate func deleteLocalNotice() {
        let center = UNUserNotificationCenter.current()
        center.removeAllDeliveredNotifications()
        center.removeAllPendingNotificationRequests()
    }
}
